//
//  OtherDetailVC.swift
//  ImGuider X
//
//  Created by llt on 2018/9/27.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit

class OtherDetailVC: BaseVC {
    
    @IBOutlet weak var tableView: UITableView!
    
    private var headView:OtherDetailHeadView!
    
    var viewmodel = OtherDetailViewModel()
    
    private var headHeight = kScreenWidth * 4 / 3
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupHeader()
        self.title = viewmodel.title
    }
    
    private func setupUI() {
        
        self.view.backgroundColor = UIColor.white
        
        
        
        let identis = ["OtherDetailTitleCell","OtherDetailPromotionCell","OtherDetailImageCell","OtherDetailLineCell","OtherDetailFacilityCell","OtherDetailOpenTimeCell","OtherDetailContactCell","OtherDetailFooterCell"]
        
        for identi in identis {
            
            tableView.register(UINib(nibName: identi, bundle: nil), forCellReuseIdentifier: identi)
        }
        
        tableView.backgroundColor = UIColor.white
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableView.automaticDimension
        
        setNavBarStyle(.whiteAlpha(0))
        
        if #available(iOS 11.0, *) {
            
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            
            self.automaticallyAdjustsScrollViewInsets = false
        }
    }
    
    private func setupHeader() {
        
        var picArray:[Any] = []
        
        if let pics = viewmodel.calendar?.pictureArray, pics.count > 0 {
            
            headHeight = kScreenWidth * 4 / 3
            picArray = pics
        } else {
            
            headHeight = kScreenWidth * 3 / 4
            picArray = [UIImage(named: "bg")!]
        }
        
        let frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: headHeight)
        
        headView = OtherDetailHeadView(frame: frame)
        
        
        /// 设置一半圆角
        let conerView = UIView(frame: CGRect.zero)
        
        conerView.backgroundColor = kThemeBgColor
        conerView.clipsToBounds = true
        
        let roundedRect = CGRect(x: 0, y: 0, width: frame.width, height: 40)
        let rounded = UIBezierPath(roundedRect: roundedRect, byRoundingCorners: [.topLeft,.topRight], cornerRadii: CGSize(width: 20, height: 20));
        
        let shape = CAShapeLayer()
        shape.path = rounded.cgPath
        
        conerView.layer.mask = shape
        
        headView.addSubview(conerView)
        
        conerView.snp.makeConstraints {
            [weak headView] maker in
            guard let `headView` = headView else { return }
            
            maker.top.equalTo(headView.snp.bottom).offset(-20)
            maker.left.equalToSuperview()
            maker.right.equalToSuperview()
            maker.bottom.equalTo(headView.snp.bottom)
        }
        
        tableView.tableHeaderView = headView
        headView.pics = picArray
    }
    
}

extension OtherDetailVC: UITableViewDataSource, UITableViewDelegate {
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return viewmodel.cellArray?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        guard let type = viewmodel.cellArray?[section] else { return 0 }
        
        if type == .line {
            
            return viewmodel.lines?.count ?? 0
        }
        
        if type == .promotion {
            
            return viewmodel.promotions?.count ?? 0
        }
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let type = viewmodel.cellArray?[indexPath.section] else { return UITableViewCell() }
        
        switch type {
        case .title:
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "OtherDetailTitleCell") as! OtherDetailTitleCell
            cell.calendar = viewmodel.calendar
            cell.openMaps = {
                
                [weak self] in
                guard let `self` = self else { return }
                
                if let coor = self.viewmodel.calendar?.coor {
                    
                    Util.tractfic(to: coor, vc: self)
                }
            }
            
            return cell
        case .mapImage:
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "OtherDetailImageCell") as! OtherDetailImageCell
            cell.mapImageView.setImage(string: viewmodel.lines?.first?.linepics?.first, placeholder: UIImage(named:"placeholder_rec")!)
            
            return cell
        case .line:
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "OtherDetailLineCell") as! OtherDetailLineCell
            
            cell.line = viewmodel.lines?[indexPath.row]
            
            cell.isTitleHidden = (indexPath.row != 0)
            cell.isLast = (indexPath.row == ((viewmodel.lines?.count ?? 0) - 1))
            
            return cell
            
        case .promotion:
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "OtherDetailPromotionCell") as! OtherDetailPromotionCell
            
            cell.promotion = viewmodel.promotions?[indexPath.row]
            cell.isTitleHidden = (indexPath.row != 0)
            cell.isLast = (indexPath.row == ((viewmodel.promotions?.count ?? 0) - 1))
            
            return cell
            
        case .facility:
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "OtherDetailFacilityCell") as! OtherDetailFacilityCell
            cell.facilities = viewmodel.facilities
            
            return cell
        case .optime:
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "OtherDetailOpenTimeCell") as! OtherDetailOpenTimeCell
            cell.openTimeLabel.text = viewmodel.openTime
            return cell
        case .contact:
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "OtherDetailContactCell") as! OtherDetailContactCell
            
            cell.contact = viewmodel.contact
            return cell
        case .footer:
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "OtherDetailFooterCell") as! OtherDetailFooterCell
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: true)
        guard let type = viewmodel.cellArray?[indexPath.section] else { return }
        
        
        if type == .line {
            
            let line = viewmodel.lines?[indexPath.row]
            
            
            if let type = line?.type,type == .citytour {
                
                let playVC = PlayCityTour()
                playVC.viewmodel.lineid = line?.lineid
                 self.navigationController?.pushViewController(playVC, animated: true)
                return
            }
            
            if line?.hascode ?? false {
                
                let playVC = PlayNumSearchVC()
                playVC.viewmodel.lineid = line?.lineid
                
                playVC.bgUrl = line?.pictureArray?.first
                self.navigationController?.pushViewController(playVC, animated: true)
            } else {
                
                let playVC = PlayScenicVC()
                playVC.viewmodel.lineid = line?.lineid
                self.navigationController?.pushViewController(playVC, animated: true)
                
                
            }
        }
        
        if type == .promotion {
            
            guard let promotion = viewmodel.promotions?[indexPath.row],
                let url = promotion.url,
                url.count > 0 else { return }
            
            let webVC = WebVC(urlstr: url)
            
            self.navigationController?.pushViewController(webVC, animated: true)
        }
    }
}

extension OtherDetailVC {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let yoffset = scrollView.contentOffset.y
        
        let alpha = yoffset / CGFloat(headHeight - kNavigationBarHeight / 2)
        
        self.setNavBarStyle(.whiteAlpha(alpha))
        
        headView.setFactor(offset: yoffset)
    }
}


